package net.rrkk.photoshow.controller;

import net.rrkk.photoshow.entity.Photo;
import net.rrkk.photoshow.service.PhotoService;
import net.rrkk.photoshow.util.ImageUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/api/photos")
public class PhotoController {
    
    @Autowired
    private PhotoService photoService;
    
    @Value("${photo.storage.path:/photo-data}")
    private String storagePath;
    
    // 创建图片
    @PostMapping
    public ResponseEntity<Photo> createPhoto(@RequestBody Photo photo) {
        Photo createdPhoto = photoService.createPhoto(photo);
        return new ResponseEntity<>(createdPhoto, HttpStatus.CREATED);
    }
    
    // 获取所有图片
    @GetMapping
    public ResponseEntity<List<Photo>> getAllPhotos() {
        List<Photo> photos = photoService.getAllPhotos();
        return new ResponseEntity<>(photos, HttpStatus.OK);
    }
    
    // 根据ID获取图片
    @GetMapping("/{id}")
    public ResponseEntity<Photo> getPhotoById(@PathVariable Long id) {
        Optional<Photo> photo = photoService.getPhotoById(id);
        if (photo.isPresent()) {
            return new ResponseEntity<>(photo.get(), HttpStatus.OK);
        } else {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
    }
    
    // 根据分类ID查找图片
    @GetMapping("/category/{categoryId}")
    public ResponseEntity<List<Photo>> getPhotosByCategoryId(@PathVariable Long categoryId) {
        List<Photo> photos = photoService.getPhotosByCategoryId(categoryId);
        return new ResponseEntity<>(photos, HttpStatus.OK);
    }
    
    // 根据标题搜索图片
    @GetMapping("/search")
    public ResponseEntity<List<Photo>> searchPhotosByTitle(@RequestParam String title) {
        List<Photo> photos = photoService.searchPhotosByTitle(title);
        return new ResponseEntity<>(photos, HttpStatus.OK);
    }
    
    // 根据文件扩展名查找图片
    @GetMapping("/extension/{fileExtension}")
    public ResponseEntity<List<Photo>> getPhotosByFileExtension(@PathVariable String fileExtension) {
        List<Photo> photos = photoService.getPhotosByFileExtension(fileExtension);
        return new ResponseEntity<>(photos, HttpStatus.OK);
    }
    
    // 获取公开图片
    @GetMapping("/public")
    public ResponseEntity<List<Photo>> getPublicPhotos() {
        List<Photo> photos = photoService.getPublicPhotos();
        return new ResponseEntity<>(photos, HttpStatus.OK);
    }
    
    // 获取非公开图片
    @GetMapping("/private")
    public ResponseEntity<List<Photo>> getPrivatePhotos() {
        List<Photo> photos = photoService.getPrivatePhotos();
        return new ResponseEntity<>(photos, HttpStatus.OK);
    }
    
    // 获取原始图片文件（公开图片或所有图片）
    @GetMapping("/file/{id}")
    public ResponseEntity<Resource> getPhotoFile(@PathVariable Long id) {
        Optional<Photo> photoOptional = photoService.getPhotoById(id);
        if (!photoOptional.isPresent()) {
            return ResponseEntity.notFound().build();
        }
        
        Photo photo = photoOptional.get();
        
        // 检查图片是否为公开图片
        if (!photo.getIsPublic()) {
            // 在实际应用中，这里应该检查用户权限
            // 为简化起见，我们返回403 Forbidden
            return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
        }
        
        Path filePath = Paths.get(photo.getFilePath());
        
        if (!Files.exists(filePath)) {
            return ResponseEntity.notFound().build();
        }
        
        try {
            FileSystemResource resource = new FileSystemResource(filePath.toFile());
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.parseMediaType(photo.getMimeType()));
            headers.setContentLength(photo.getFileSize());
            headers.setContentDispositionFormData("attachment", photo.getFileName());
            
            return new ResponseEntity<>(resource, headers, HttpStatus.OK);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }
    
    // 获取指定尺寸的图片（公开图片或所有图片）
    @GetMapping("/file/{id}/size")
    public ResponseEntity<byte[]> getResizedPhotoFile(
            @PathVariable Long id,
            @RequestParam(required = false, defaultValue = "0") int width,
            @RequestParam(required = false, defaultValue = "0") int height) {
        Optional<Photo> photoOptional = photoService.getPhotoById(id);
        if (!photoOptional.isPresent()) {
            return ResponseEntity.notFound().build();
        }
        
        Photo photo = photoOptional.get();
        
        // 检查图片是否为公开图片
        if (!photo.getIsPublic()) {
            // 在实际应用中，这里应该检查用户权限
            // 为简化起见，我们返回403 Forbidden
            return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
        }
        
        Path filePath = Paths.get(photo.getFilePath());
        
        if (!Files.exists(filePath)) {
            return ResponseEntity.notFound().build();
        }
        
        try {
            // 读取原始图片
            BufferedImage originalImage = ImageIO.read(filePath.toFile());
            
            // 调整图片尺寸
            BufferedImage resizedImage = ImageUtils.resizeImage(originalImage, width, height);
            
            // 将图片转换为字节数组
            String format = ImageUtils.getImageFormat(photo.getMimeType());
            byte[] imageBytes = ImageUtils.imageToByteArray(resizedImage, format);
            
            // 设置响应头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.parseMediaType(photo.getMimeType()));
            headers.setContentLength(imageBytes.length);
            
            return new ResponseEntity<>(imageBytes, headers, HttpStatus.OK);
        } catch (IOException e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }
    
    // 获取带水印的图片（公开图片或所有图片）
    @GetMapping("/file/{id}/watermark")
    public ResponseEntity<byte[]> getWatermarkedPhotoFile(
            @PathVariable Long id,
            @RequestParam(required = false, defaultValue = "Sample Watermark") String text) {
        Optional<Photo> photoOptional = photoService.getPhotoById(id);
        if (!photoOptional.isPresent()) {
            return ResponseEntity.notFound().build();
        }
        
        Photo photo = photoOptional.get();
        
        // 检查图片是否为公开图片
        if (!photo.getIsPublic()) {
            // 在实际应用中，这里应该检查用户权限
            // 为简化起见，我们返回403 Forbidden
            return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
        }
        
        Path filePath = Paths.get(photo.getFilePath());
        
        if (!Files.exists(filePath)) {
            return ResponseEntity.notFound().build();
        }
        
        try {
            // 读取原始图片
            BufferedImage originalImage = ImageIO.read(filePath.toFile());
            
            // 添加水印
            BufferedImage watermarkedImage = ImageUtils.addWatermark(originalImage, text);
            
            // 将图片转换为字节数组
            String format = ImageUtils.getImageFormat(photo.getMimeType());
            byte[] imageBytes = ImageUtils.imageToByteArray(watermarkedImage, format);
            
            // 设置响应头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.parseMediaType(photo.getMimeType()));
            headers.setContentLength(imageBytes.length);
            
            return new ResponseEntity<>(imageBytes, headers, HttpStatus.OK);
        } catch (IOException e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }
    
    // 更新图片
    @PutMapping("/{id}")
    public ResponseEntity<Photo> updatePhoto(@PathVariable Long id, @RequestBody Photo photoDetails) {
        Photo updatedPhoto = photoService.updatePhoto(id, photoDetails);
        if (updatedPhoto != null) {
            return new ResponseEntity<>(updatedPhoto, HttpStatus.OK);
        } else {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
    }
    
    // 删除图片
    @DeleteMapping("/{id}")
    public ResponseEntity<HttpStatus> deletePhoto(@PathVariable Long id) {
        photoService.deletePhoto(id);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }
}